package com.bnlr.lrparking.appui.mine.mygnd;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.appui.login.VerificaActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.lrparking.widget.refresh.RefreshHolderUtil;
import com.bnlr.lrparking.widget.refresh.XRefreshLayout;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * package: com.bnlr.lrparking.appui.mine.gndLock
 * filename: MyGNDLockAct
 * author: Licy
 * date: 2018/11/20
 * description: 我的地锁
 */
public class MyGNDLockAct extends BaseActivity {

    public static final String TAG = MyGNDLockAct.class.getSimpleName() + "------>";

    @BindView(R.id.gndlock_recyclerView)
    RecyclerView gndlockRecyclerView;
    @BindView(R.id.gndlock_refresh)
    XRefreshLayout gndlockRefresh;

    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.iv_nav_back)
    ImageView ivNavBack;

    @BindView(R.id.ll_hint)
    LinearLayout noData;
    @BindView(R.id.iv_hint)
    ImageView noDataivhint;
    @BindView(R.id.tv_hint_tips)
    TextView noDatatvHint;

    private Unbinder unbinder;
    private GndLockAdapter adapter;
    private List<GndLockBean.DataBean> mDataList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gndlock);
        unbinder = ButterKnife.bind(this);
        initView();

    }

    public void initView() {
        LogUtils.i(TAG + "init view start! ");
        tvNavTitle.setText(R.string.gndLock_title);
        ivNavBack.setOnClickListener(this);
        // 设置recycle view
        mDataList = new ArrayList<>();
        adapter = new GndLockAdapter(R.layout.item_gndlock_layout, mDataList);
        gndlockRecyclerView.setAdapter(adapter);
        gndlockRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        gndlockRecyclerView.setItemAnimator(new DefaultItemAnimator());
        gndlockRecyclerView.addItemDecoration(new SpaceItemDecoration(10));
        gndlockRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

                switch (view.getId()) {
                    // 关闭地锁
                    case R.id.gnd_close:
                        ToastUtils.showShort("点击关闭地锁");
                        break;
                    // 打开地锁
                    case R.id.gnd_open:
                        ToastUtils.showShort("点击打开地锁");
                        break;
                    default:
                        break;
                }
            }
        });

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

                switch (view.getId()) {
                    // 关闭地锁  1打开 2关闭 0未启用
                    case R.id.gnd_close:
                        ToastUtils.showShort("点击关闭地锁");
                        sendOpenOrClose(mDataList.get(i).getLockid(), 2, mDataList.get(i).getParkingId());
                        break;
                    // 打开地锁
                    case R.id.gnd_open:
                        ToastUtils.showShort("点击打开地锁");
                        sendOpenOrClose(mDataList.get(i).getLockid(), 1, mDataList.get(i).getParkingId());
                        break;
                    default:
                        break;
                }
            }
        });

        // 设置下拉刷新
        gndlockRefresh.setRefreshViewHolder(RefreshHolderUtil.getRefreshHolder(this));
        gndlockRefresh.setDelegate(new XRefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(XRefreshLayout refreshLayout) {
                getData();
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(XRefreshLayout refreshLayout) {
                return false;
            }
        });
        gndlockRefresh.beginRefreshing();
    }

    /**
     * 切换页面
     *
     * @param isHaveData 是否有数据
     */
    public void switchView(boolean isHaveData) {
        LogUtils.i("switchView start ! isHaveData ", isHaveData);

        // 判断有无数据
        if (isHaveData) {
            gndlockRefresh.setVisibility(View.VISIBLE);
            noData.setVisibility(View.GONE);
            noDatatvHint.setVisibility(View.GONE);
            noDataivhint.setVisibility(View.GONE);
        } else {
            gndlockRefresh.setVisibility(View.GONE);
            noData.setVisibility(View.VISIBLE);
            noDatatvHint.setVisibility(View.VISIBLE);
            noDatatvHint.setText(R.string.gndLock_noData_tip);
            noDataivhint.setVisibility(View.VISIBLE);
            noDataivhint.setImageResource(R.mipmap.gndlock_nodata);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_nav_back:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        LogUtils.i(TAG + "onDestroy start!");
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }


    @Override
    public void getData() {

        try {
            mRequest = NoHttp.createStringRequest(Urls.GROUNDLOCK, LrConstant.POST);
            mRequest.add("action", "GetLockList");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));

            CallServer.getRequestInstance().add(this, mRequest, new CustomHttpListener<GndLockBean>(this, true, GndLockBean.class) {
                @Override
                public void doWork(GndLockBean data, String code) {
                    LogUtils.i("GndLockBean", data.toString());
                    if (TextUtils.equals("1", code)) {
                        if (adapter != null) {
                            if (data.getData().size() != 0) {
                                switchView(true);
                                mDataList.clear();
                                mDataList.addAll(data.getData());
                                adapter.notifyDataSetChanged();
                            } else {
                                switchView(false);
                            }
                        }
                    }
                }

                @Override
                public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                    if (gndlockRefresh != null) {
                        gndlockRefresh.endRefreshing();
                    }

                    switchView(isSucceed);
//                    try {
//                        if (!TextUtils.equals("1", code) && (obj.getString("msg").contains("用户已在其他手机上登录") ||
//                                obj.getString("msg").contains("请重新登录"))) {
//                            final CarCommon carCommon = new CarCommon();
//                            carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
//                                @Override
//                                public void setSure() {
//                                    Intent intent = new Intent(MyGNDLockAct.this, VerificaActivity.class);
//                                    startActivity(intent);
//                                }
//                            });
//                            carCommon.ReminderDialog(MyGNDLockAct.this, "登录信息已过期，是否重新登录？", "下线通知", "立即登录");
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                }
            }, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送指令 关闭或打开地锁
     *
     * @param status 1打开 2关闭 0未启用
     */
    public void sendOpenOrClose(int lockid, int status, int parkSpaceid) {
        LogUtils.i("sendOpenOrClose start！");

        try {
            mRequest = NoHttp.createStringRequest(Urls.GROUNDLOCK, LrConstant.POST);
            mRequest.add("action", "GetLockList");
            mRequest.add("lockid", lockid);
            mRequest.add("openORshut", status);
            mRequest.add("parkSpaceid", parkSpaceid);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));


            CallServer.getRequestInstance().add(this, mRequest, new CustomHttpListener<GndLockBean>(this, true, GndLockBean.class) {
                @Override
                public void doWork(GndLockBean data, String code) {
                    if (TextUtils.equals("1", code)) {
                        if (adapter != null) {
                            if (data != null) {
                                LogUtils.i(data.toString());
                                // TODO 打开或关闭后的处理
                            }
                        }
                    } else {
                        ToastUtils.showShort(data.getMsg() + "");
                    }
                }

                @Override
                public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                    if (gndlockRefresh != null) {
                        gndlockRefresh.endRefreshing();
                    }
                    try {
                        if (!TextUtils.equals("1", code) && (obj.getString("msg").contains("用户已在其他手机上登录") ||
                                obj.getString("msg").contains("请重新登录"))) {
                            final CarCommon carCommon = new CarCommon();
                            carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                                @Override
                                public void setSure() {
                                    Intent intent = new Intent(MyGNDLockAct.this, VerificaActivity.class);
                                    startActivity(intent);
                                }
                            });
                            carCommon.ReminderDialog(MyGNDLockAct.this, "登录信息已过期，是否重新登录？", "下线通知", "立即登录");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, false);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        int mSpace;

        /**
         * Retrieve any offsets for the given item. Each field of <code>outRect</code> specifies
         * the number of pixels that the item view should be inset by, similar to padding or margin.
         * The default implementation sets the bounds of outRect to 0 and returns.
         * <p>
         * <p>
         * If this ItemDecoration does not affect the positioning of item views, it should set
         * all four fields of <code>outRect</code> (left, top, right, bottom) to zero
         * before returning.
         * <p>
         * <p>
         * If you need to access Adapter for additional data, you can call
         * {@link RecyclerView#getChildAdapterPosition(View)} to get the adapter position of the
         * View.
         *
         * @param outRect Rect to receive the output.
         * @param view    The child view to decorate
         * @param parent  RecyclerView this ItemDecoration is decorating
         * @param state   The current state of RecyclerView.
         */
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.bottom = mSpace;
//            if (parent.getChildAdapterPosition(view) == 0) {
//                outRect.top = mSpace;
//            }

        }

        public SpaceItemDecoration(int space) {
            this.mSpace = space;
        }
    }
}

